package com.wzk.travelspringboot.utils;

import cn.hutool.core.util.StrUtil;
import com.wzk.travelspringboot.common.RedisConstant;
import com.wzk.travelspringboot.dto.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/18 14:13
 */
@Component
@RequiredArgsConstructor
public class RequestLimitUtil {

    private final StringRedisTemplate stringRedisTemplate;

    //实现请求接口限流 10s内只能允许5次请求
    public synchronized boolean reqLimit(String keySuffix){
        String key = RedisConstant.REQUEST_LIMIT + keySuffix;
        Boolean b = stringRedisTemplate.hasKey(key);
        if (Boolean.FALSE.equals(b)){
            //key不存在 插入并且添加过期时间5s
            stringRedisTemplate.opsForValue().set(key,1+"",RedisConstant.REQUEST_LIMIT_TIME, TimeUnit.SECONDS);
        }else {
            //key存在判断key是否到达了阈值
            String s = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(s) && Integer.valueOf(s) == 5){
                return false;
            }else {
                stringRedisTemplate.opsForValue().increment(key);
            }
        }
        return true;
    }

}
